package com.solution.pc.promotion;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.solution.admin.coupon.constants.CouponConstants;
import com.solution.admin.coupon.entity.CouponEntity;
import com.solution.admin.coupon.service.CouponService;
import com.solution.admin.promotion.constants.PromotionConstants;
import com.solution.admin.promotion.entity.PromotionEntity;
import com.solution.admin.promotion.entity.PromotionProductEntity;
import com.solution.admin.promotion.entity.PromotionRuleDiscountEntity;
import com.solution.admin.promotion.entity.PromotionRuleGiftEntity;
import com.solution.admin.promotion.entity.PromotionRuleReduceEntity;
import com.solution.admin.promotion.entity.PromotionRulesEntity;
import com.solution.admin.promotion.service.PromotionProductService;
import com.solution.admin.promotion.service.PromotionService;
import com.solution.admin.promotion.service.PromotionTargetService;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.NumberUtil;
import com.solution.pc.shoppingcart.entity.ShoppingCartEntity;

@Component
public class PromotionCheckUtil {

	@Autowired
	private PromotionProductService promotionProductService;

	@Autowired
	private PromotionTargetService promotionTargetService;

	@Autowired
	private PromotionService promotionService;

	@Autowired
	private CouponService couponService;

	/**
	 * 检查商品是否参加活动，计算活动结果 处理活动的结果是设置到每个购物车item记录中的
	 * 
	 * @param productCodeList
	 * @param cartList
	 * @param customerId
	 * @author llp
	 */
	public boolean checkPromotion(List<ShoppingCartEntity> cartList, List<String> productCodeList, long customerId) {
		// 是否参与活动，默认没有
		boolean isOnPromotion = false;

		Map<String, Object> param = new HashMap<String, Object>();
		// 查询商品是否参加活动
		Map<String, PromotionRulesEntity> promotionMap = new HashMap<String, PromotionRulesEntity>();
		if (productCodeList.size() > 0) {
			param.clear();
			param.put("productCodeList", productCodeList);
			param.put("productType", PromotionConstants.PROMOTION_PRODUCT_TYPE.NORMAL.getCode());
			// 批量查询结算商品参加了哪些活动
			List<PromotionProductEntity> ppList = promotionProductService.listPromotionProduct(param);
			if (ppList != null && ppList.size() > 0) {
				for (PromotionProductEntity ppe : ppList) {
					// 逐个商品判断该客户是否属于活动对象
					param.clear();
					param.put("customerId", customerId);
					param.put("promotionId", ppe.getPromotionId());
					boolean flag = promotionTargetService.existsInPromotionTarget(param);
					if (flag) {
						// 如果属于活动对象，再查询活动规则 (活动规格会进行缓存)
						PromotionRulesEntity promotionRules = promotionService.listPromotionRule(ppe.getPromotionId());
						if (promotionRules != null) {
							promotionMap.put(ppe.getProductCode(), promotionRules);
						}
					}
				}
			}
		}

		// 【合同购物车中商品】
		// 合并购物车中同编号的商品，处理以下场景
		// 如：（1） 001 iphonex 黑色 X 1 8000元 （2） 001 iphonex 红色 X 1 8500 ，
		// 这个商品在购物车中由于规格不同存在两个条目 ，类似情况需要按商品编号合并金额后，再计算优惠
		Map<String, ShoppingCartEntity> itemCartMap = new HashMap<String, ShoppingCartEntity>();
		if (cartList != null && cartList.size() > 0) {
			for (ShoppingCartEntity cartItem : cartList) {
				if (itemCartMap.containsKey(cartItem.getProductCode())) {
					ShoppingCartEntity tmpSce = itemCartMap.get(cartItem.getProductCode());
					BigDecimal tmpMoney = tmpSce.getProductPrice().multiply(new BigDecimal(tmpSce.getBuyNum()));
					tmpMoney = tmpMoney.add(cartItem.getProductPrice().multiply(new BigDecimal(cartItem.getBuyNum())));
					tmpSce.setSubTotalProductPrice(tmpMoney);
					// 购物的数量
					// tmpSce.setBuyNum(tmpSce.getBuyNum() +
					// cartItem.getBuyNum());
				} else {
					cartItem.setSubTotalProductPrice(cartItem.getProductPrice().multiply(new BigDecimal(cartItem.getBuyNum())));
					itemCartMap.put(cartItem.getProductCode(), cartItem);
				}
			}
		}

		// 循环商品设置优惠活动信息
		if (itemCartMap.size() > 0) {
			for (Map.Entry<String, ShoppingCartEntity> scEntry : itemCartMap.entrySet()) {
				ShoppingCartEntity cartItem = scEntry.getValue();
				// 单个商品购买金额小计
				BigDecimal cartItemMoney = cartItem.getSubTotalProductPrice();
				// 单个商品活动满减金额
				BigDecimal itemReduceMoney = new BigDecimal(0);
				if (promotionMap.containsKey(cartItem.getProductCode())) {
					// 取出活动规则
					PromotionRulesEntity promotionRules = promotionMap.get(cartItem.getProductCode());
					// 取出活动基本信息
					PromotionEntity promotionEntity = promotionRules.getPromtEntity();
					// 活动描述
					StringBuffer promotionDescBuf = new StringBuffer();
					if (PromotionConstants.PROMOTION_TYPE.REDUCE.getCode().equals(String.valueOf(promotionEntity.getPromotionType()))) {
						// 【1】满减
						// 取出满减规则列表
						List<PromotionRuleReduceEntity> reduceList = promotionRules.getReduceList();
						if (reduceList != null && reduceList.size() == 1) {
							// 只有一条记录，可能是无上限的递增式规则设置
							PromotionRuleReduceEntity reduce = reduceList.get(0);
							if (reduce.getIsLimit() == PromotionConstants.PROMOTION_RULE_LIMIT_TYPE.UNLIMTED.getCode()) {
								// 上不封顶 折扣金额* (商品项小计/折扣最低标准)
								itemReduceMoney = reduce.getReduceMoney().multiply(
								        new BigDecimal((cartItemMoney.intValue() / reduce.getOrderMoney().intValue())));
								promotionDescBuf.append("满").append(NumberUtil.formatToInteger(reduce.getOrderMoney())).append("减")
								        .append(NumberUtil.formatToInteger(reduce.getReduceMoney())).append("元(上不封顶)");
							} else {
								// 满足金额取满减金额
								if (cartItemMoney.doubleValue() >= reduce.getOrderMoney().doubleValue()) {
									itemReduceMoney = reduce.getReduceMoney();
									promotionDescBuf.append("满").append(NumberUtil.formatToInteger(reduce.getOrderMoney())).append("减")
									        .append(NumberUtil.formatToInteger(reduce.getReduceMoney()));
								}
							}
						} else if (reduceList != null && reduceList.size() > 1) {
							// 大于1条，是有多条满减规则
							for (PromotionRuleReduceEntity reduce : reduceList) {
								if (cartItemMoney.doubleValue() >= reduce.getOrderMoney().doubleValue()) {
									itemReduceMoney = reduce.getReduceMoney();
									promotionDescBuf.append("满").append(NumberUtil.formatToInteger(reduce.getOrderMoney())).append("减")
									        .append(NumberUtil.formatToInteger(reduce.getReduceMoney())).append("元");
								}
							}
						}
						// 拼接满减活动的检查结果
						List<PromotionProductEntity> itemReduceList = new ArrayList<PromotionProductEntity>();
						PromotionProductEntity tmpReduce = new PromotionProductEntity();
						// 活动名称
						tmpReduce.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.REDUCE.getName());
						// 满减金额
						tmpReduce.setReduceMoney(itemReduceMoney);
						itemReduceList.add(tmpReduce);
						// 设置到购物车item记录中
						cartItem.setReduceList(itemReduceList);
						cartItem.setPromotionDesc(promotionDescBuf.toString());
						cartItem.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.REDUCE.getName());
						// 参与了活动
						isOnPromotion = true;
					} else if (PromotionConstants.PROMOTION_TYPE.GIFT.getCode().equals(String.valueOf(promotionEntity.getPromotionType()))) {
						// 【2】满赠活动
						// 取出满赠规则列表
						List<PromotionRuleGiftEntity> giftList = promotionRules.getGiftList();
						if (giftList != null && giftList.size() > 0) {
							// 循环满赠规则,一条购物车item最多只一满足一个(匹配金额的)规则
							for (PromotionRuleGiftEntity gift : giftList) {
								if (cartItemMoney.doubleValue() >= gift.getOrderMoney().doubleValue()) {
									promotionDescBuf.append("满").append(NumberUtil.formatToInteger(gift.getOrderMoney()));
									if (PromotionConstants.PROMOTION_GIFT_TYPE.GIFT.getCode().equals(gift.getGiftType())) {
										// 【2.1】赠品
										param.clear();
										param.put("promotionRuleId", gift.getId());
										param.put("productType", PromotionConstants.PROMOTION_PRODUCT_TYPE.GIFT.getCode());
										// 查询赠品
										List<PromotionProductEntity> giftProductList = promotionProductService.listPromotionProduct(param);
										if (giftProductList != null && giftProductList.size() > 0) {
											// 拼接满赠（送赠品）列表
											List<PromotionProductEntity> itemGiftProductList = new ArrayList<PromotionProductEntity>();
											for (PromotionProductEntity giftProduct : giftProductList) {
												PromotionProductEntity tmpGift = new PromotionProductEntity();
												// 【满赠】
												tmpGift.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.GIFT.getName());
												// 赠品类型 - 赠品
												tmpGift.setGiftType(PromotionConstants.PROMOTION_GIFT_TYPE.GIFT.getCode());
												// 赠品编码
												tmpGift.setProductCode(giftProduct.getProductCode());
												// 赠品名称
												tmpGift.setProductName(giftProduct.getProductName());
												// 数量默认为1
												tmpGift.setGiftNum(1);
												itemGiftProductList.add(tmpGift);
												promotionDescBuf.append("赠").append(giftProduct.getProductName()).append(" X 1; ");
											}
											cartItem.setGiftList(itemGiftProductList);
										}
									} else if (PromotionConstants.PROMOTION_GIFT_TYPE.COUPON.getCode().equals(gift.getGiftType())) {
										// 【2.2】赠品优惠券
										List<PromotionProductEntity> itemCouponList = new ArrayList<PromotionProductEntity>();
										PromotionProductEntity tmpCoupon = new PromotionProductEntity();
										tmpCoupon.setGiftType(PromotionConstants.PROMOTION_GIFT_TYPE.COUPON.getCode());
										tmpCoupon.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.GIFT.getName());
										tmpCoupon.setCouponId(gift.getCouponId());
										tmpCoupon.setGiftNum(1);
										// 赠送优惠券的金额
										long couponId = gift.getCouponId();
										CouponEntity coupon = couponService.getCouponById(couponId);
										StringBuffer validity = new StringBuffer();
										if (coupon.getTimeType().equals(CouponConstants.TimeType.TIME_START_STOP)) {
											validity.append(DateUtils.formatDate(coupon.getBeginTime())).append("~")
											        .append(DateUtils.formatDate(coupon.getEndTime()));
										} else {
											validity.append(coupon.getLimitDay()).append("天");
										}
										promotionDescBuf.append("赠").append(coupon.getCouponName()).append(validity).append(" X 1; ");
										itemCouponList.add(tmpCoupon);
										cartItem.setGiftList(itemCouponList);
									} else if (PromotionConstants.PROMOTION_GIFT_TYPE.POINTS.getCode().equals(gift.getGiftType())) {
										// 【2.3】赠品积分
										List<PromotionProductEntity> itemPointsList = new ArrayList<PromotionProductEntity>();
										PromotionProductEntity tmpPoints = new PromotionProductEntity();
										tmpPoints.setGiftType(PromotionConstants.PROMOTION_GIFT_TYPE.POINTS.getCode());
										tmpPoints.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.GIFT.getName());
										// 赠品积分数量
										tmpPoints.setPoints(gift.getGiftValue());
										promotionDescBuf.append("赠").append(NumberUtil.formatToInteger(gift.getGiftValue())).append("积分");
										itemPointsList.add(tmpPoints);
										cartItem.setGiftList(itemPointsList);
									}
									cartItem.setPromotionDesc(promotionDescBuf.toString());
									cartItem.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.GIFT.getName());
									// 参与了活动
									isOnPromotion = true;
								}
							}
						}
					} else if (PromotionConstants.PROMOTION_TYPE.DISCOUNT.getCode().equals(String.valueOf(promotionEntity.getPromotionType()))) {
						// 【3】折扣
						List<PromotionRuleDiscountEntity> discountList = promotionRules.getDiscountList();
						if (discountList != null && discountList.size() > 0) {
							for (PromotionRuleDiscountEntity discount : discountList) {
								if (cartItemMoney.doubleValue() >= discount.getOrderMoney().doubleValue()) {
									List<PromotionProductEntity> itemDiscountList = new ArrayList<PromotionProductEntity>();
									PromotionProductEntity tmpDiscount = new PromotionProductEntity();
									tmpDiscount.setPromotionTypeName(PromotionConstants.PROMOTION_TYPE.DISCOUNT.getName());
									// 折扣
									tmpDiscount.setDiscount(discount.getDiscount());
									promotionDescBuf.append("满").append(NumberUtil.formatToInteger(discount.getOrderMoney())).append("享受")
									        .append(NumberUtil.formatToDiscount(discount.getDiscount())).append("折优惠");
									itemDiscountList.add(tmpDiscount);
									cartItem.setDiscountList(itemDiscountList);
									cartItem.setPromotionDesc(promotionDescBuf.toString());
									// 参与了活动
									isOnPromotion = true;
								}
							}
						}
					}
				}
			}
		}
		return isOnPromotion;
	}
}
